
package com.hmall.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.exception.BizIllegalException;
import com.hmall.common.utils.BeanUtils;
import com.hmall.item.domain.dto.ItemDTO;
import com.hmall.item.domain.dto.OrderDetailDTO;
import com.hmall.item.domain.po.Item;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.service.IItemService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;


@Service
public class ItemServiceImpl extends ServiceImpl<ItemMapper, Item> implements IItemService {

    // 扣减库存
    @Override
    @Transactional
    public void deductStock(List<OrderDetailDTO> items) {
        String sqlStatement = "com.hmall.item.mapper.ItemMapper.updateStock";
        boolean r = false;
        //executeBatch作用是批量执行sql这里是批量更新库存 参数1是要更新的数据 参数2是更新的sql
        try {
            r = executeBatch(items, (sqlSession, entity) -> sqlSession.update(sqlStatement, entity));
        } catch (Exception e) {
            throw new BizIllegalException("更新库存异常，可能是库存不足!", e);
        }
        if (!r) {
            throw new BizIllegalException("库存不足！");
        }
    }

    // 根据id查询商品
    @Override
    public List<ItemDTO> queryItemByIds(Collection<Long> ids) {
        return BeanUtils.copyList(listByIds(ids), ItemDTO.class);
    }

    // 批量恢复库存
    @Override
    @Transactional
    public void restoreStock(List<OrderDetailDTO> items) {
        String sqlStatement = "com.hmall.item.mapper.ItemMapper.restoreStock";
        boolean r = false;
        try {
            //executeBatch作用是批量执行sql这里是批量更新库存 参数1是要更新的数据 参数2是更新的sql
            r = executeBatch(items, (sqlSession, entity) -> sqlSession.update(sqlStatement, entity));
        } catch (Exception e) {
            throw new BizIllegalException("恢复库存异常", e);
        }
        if (!r) {
            throw new BizIllegalException("恢复库存失败");
        }

        //方法二
        /*for (OrderDetailDTO orderDetailDTO : items) {
            //先查询需要恢复库存的商品
            Item item = lambdaQuery().eq(Item::getId, orderDetailDTO.getItemId()).one();
            //然后在基础上恢复库存
            lambdaUpdate().set(Item::getStock, item.getStock()+ orderDetailDTO.getNum())
                    .eq(Item::getId, orderDetailDTO.getItemId())
                    .update();
        }*/


    }


}
